package com.zhiche.lisa.lspm.service.fleet.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zhiche.lisa.core.enums.IntegrationEnum;
import com.zhiche.lisa.core.enums.SystemEnum;
import com.zhiche.lisa.core.enums.TableStatusEnum;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.utils.Account.AccountUtil;
import com.zhiche.lisa.core.utils.Account.JwtAccountVO;
import com.zhiche.lisa.core.utils.HttpClientUtil;
import com.zhiche.lisa.core.utils.RegexUtil;
import com.zhiche.lisa.core.utils.SnowFlakeId;
import com.zhiche.lisa.core.utils.qiniu.config.QiniuConfig;
import com.zhiche.lisa.core.utils.qiniu.util.QiniuUtils;
import com.zhiche.lisa.core.utils.redislog.RedisLogUtil;
import com.zhiche.lisa.lspm.config.LspmProperties;
import com.zhiche.lisa.lspm.dao.mapper.fleet.FleetMapper;
import com.zhiche.lisa.lspm.dao.model.driver.Driver;
import com.zhiche.lisa.lspm.dao.model.driver.DriverCheckin;
import com.zhiche.lisa.lspm.dao.model.fleet.*;
import com.zhiche.lisa.lspm.dao.model.lsp.LspInfo;
import com.zhiche.lisa.lspm.dao.model.sys.User;
import com.zhiche.lisa.lspm.dto.ArFundDTO;
import com.zhiche.lisa.lspm.dto.FleetToOliCardDTO;
import com.zhiche.lisa.lspm.dto.FleetToOtmDTO;
import com.zhiche.lisa.lspm.dto.LspInfoDTO;
import com.zhiche.lisa.lspm.service.driver.IDriverCheckinService;
import com.zhiche.lisa.lspm.service.driver.IDriverService;
import com.zhiche.lisa.lspm.service.fleet.*;
import com.zhiche.lisa.lspm.service.lsp.LspInfoService;
import com.zhiche.lisa.lspm.service.sys.impl.UserServiceDiy;
import com.zhiche.lisa.lspm.service.utils.IntegrationUtil;
import com.zhiche.lisa.lspm.service.utils.MdmUtil;
import com.zhiche.lisa.lspm.service.utils.UaaUtil;
import com.zhiche.lisa.lspm.vo.common.AccountVO;
import com.zhiche.lisa.lspm.vo.fleet.*;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * <p>
 * 车队 服务实现类
 * </p>
 *
 * @author liuanshun
 * @since 2018-07-18
 */
@Service
public class FleetServiceImpl extends ServiceImpl<FleetMapper, Fleet> implements IFleetService {
    private static final Logger LOGGER = LoggerFactory.getLogger(IFleetService.class);
    @Autowired
    private IFleetService fleetService;
    @Autowired
    private FleetAdminService fleetAdminService;
    @Autowired
    private IFleetBindService fleetBindService;
    @Autowired
    private LspInfoService lspInfoService;
    @Autowired
    private UaaUtil uaaUtil;
    @Autowired
    private MdmUtil mdmUtil;
    @Autowired
    private SnowFlakeId snowFlakeId;
    @Autowired
    private LspmProperties properties;
    @Autowired
    private IDriverCheckinService driverCheckinService;
    @Autowired
    private IDriverService driverService;
    @Autowired
    private UserServiceDiy userServiceDiy;


    @Autowired
    private IntegrationUtil integrationUtil;
    @Autowired
    private FleetBankAccountService fleetBankAccountService;
    @Autowired
    private FleetLicenseAttachService fleetLicenseAttachService;
    @Autowired
    private QiniuConfig qiniuConfig;

    @Value("${integration.url}")
    private String integrationUrl;

    @Value("${integration.socketTimeout}")
    private Integer socketTimeout;

    @Value("${integration.supplierPushErpUrl}")
    private String supplierPushErpUrl;

    @Value("${integration.fleetPushPayUrl}")
    private String fleetPushPayUrl;

    @Value("${lisa.tms.fleetWaybillUrl}")
    private String fleetWaybillUrl;

    @Value("${lisa.tms.driverWaybillUrl}")
    private String driverWaybillUrl;

    @Value("${logRedis.isTest}")
    private boolean isTest;
    /**
     * 分页查询公司车队
     */
    @Override
    public Page<FleetLineVO> fleetLinePage(Page<FleetLineVO> page, String authorization) {
        try {
            String accountTenant = "";
            JwtAccountVO jwtAccountVO = AccountUtil.getAccountInfoFromSecurityContext();
            if (Objects.nonNull(jwtAccountVO)) {
                accountTenant = jwtAccountVO.getTenantId();
            }
            if (Strings.isNullOrEmpty(accountTenant)) throw new BaseException("未获取到登陆的公司信息");
            EntityWrapper<FleetLineVO> ew = buildCondition(page.getCondition());
            ew.eq("tenant_id", accountTenant);
            List<FleetLineVO> list = baseMapper.queryFleetBindPage(page, ew);
            List<FleetTypeVO> listFleetType = mdmUtil.getAllFleetTypeByType();
            //审核人信息转换
            for (FleetLineVO fleetLineVO :
                    list) {
                if (!Strings.isNullOrEmpty(fleetLineVO.getCreator())) {
                    AccountVO accountVO = uaaUtil.getAccountById(fleetLineVO.getCreator(), authorization);
                    if (Objects.nonNull(accountVO)) {
                        fleetLineVO.setCreator(accountVO.getIdentifier());
                        fleetLineVO.setCreatorLspName(accountVO.getCorpName());
                    }
                }
                for (FleetTypeVO fleetType : listFleetType) {
                    if (fleetType.getId().equals(fleetLineVO.getFleetTypeId())) {
                        fleetLineVO.setFleetType(fleetType.getValue());
                    }
                }
            }
            page.setRecords(list);
            return page;
        } catch (BaseException e) {
            LOGGER.error("FleetServiceImpl.fleetLinePage:" + e.getMessage());
            throw e;
        } catch (Exception e) {
            LOGGER.error("FleetServiceImpl.fleetLinePage:" + e.getMessage());
            throw new BaseException("获取车队信息异常");
        }
    }

    /**
     * 分页查询承运商车队
     */
    @Override
    public Page<FleetLineVO> lspFleetLinePage(Page<FleetLineVO> page, String authorization) {
        try {
            String accountTenant = "";
            JwtAccountVO jwtAccountVO = AccountUtil.getAccountInfoFromSecurityContext();
            if (Objects.nonNull(jwtAccountVO)) {
                accountTenant = jwtAccountVO.getTenantId();
            }
            if (Strings.isNullOrEmpty(accountTenant)) throw new BaseException("未获取到登陆的公司信息");
            EntityWrapper<FleetLineVO> ew = buildCondition(page.getCondition());
            //不查询自己的承运商车队
            ew.ne("tenant_id", accountTenant);
            //只查询自己创建的车队
            List<String> accountIds = Lists.newArrayList();
            List<AccountVO> accountVOS = uaaUtil.getListAdminAccountUrl(authorization);
            List<FleetTypeVO> listFleetType = mdmUtil.getAllFleetTypeByType();
            if (!CollectionUtils.isEmpty(accountVOS)) {
                for (AccountVO accountVO : accountVOS) {
                    accountIds.add(accountVO.getId());
                }
            }
            ew.in("creator", accountIds);
            List<FleetLineVO> list = baseMapper.queryFleetBindPage(page, ew);
            for (FleetLineVO fleetLineVO : list) {
                if (!Strings.isNullOrEmpty(fleetLineVO.getCreator())) {
                    AccountVO accountVO = uaaUtil.getAccountById(fleetLineVO.getCreator(), authorization);
                    if (Objects.nonNull(accountVO)) {
                        fleetLineVO.setCreator(accountVO.getIdentifier());
                        fleetLineVO.setCreatorLspName(accountVO.getCorpName());
                    }
                }
                for (FleetTypeVO fleetType : listFleetType) {
                    if (fleetType.getId().equals(fleetLineVO.getFleetTypeId())) {
                        fleetLineVO.setFleetType(fleetType.getValue());
                    }
                }
            }
            page.setRecords(list);
            return page;
        } catch (BaseException e) {
            LOGGER.error("FleetServiceImpl.lspFleetLinePage:" + e.getMessage());
            throw e;
        } catch (Exception e) {
            LOGGER.error("FleetServiceImpl.lspFleetLinePage:" + e.getMessage());
            throw new BaseException("获取车队信息异常");
        }
    }

    /**
     * 新增车队
     */
    @Override
    @Transactional
    public void insertFleet(Fleet fleetLine, String authorization) {
        if (Objects.isNull(fleetLine)) {
            throw new BaseException("数据不能为空！");
        }
        JwtAccountVO jwtAccountVO = AccountUtil.getAccountInfoFromSecurityContext();
        if (Objects.isNull(jwtAccountVO)) throw new BaseException("未获取到登录信息");
        EntityWrapper<LspInfo> lspEw = new EntityWrapper<>();
        if (Objects.isNull(fleetLine.getLspId())) {
            //若未指定承运商，则绑定至登录用户
            lspEw.eq("tenant_id", jwtAccountVO.getTenantId());
        } else {
            lspEw.eq("id", fleetLine.getLspId());
        }
        List<LspInfo> lspInfo = lspInfoService.selectList(lspEw);
        if (CollectionUtils.isEmpty(lspInfo)) throw new BaseException("未获取到登录承运商信息");
        fleetLine.setTenantId(lspInfo.get(0).getTenantId());
        fleetLine.setLspId(lspInfo.get(0).getId());
        if (!Strings.isNullOrEmpty(fleetLine.getFleetDescribe()))
            if (!RegexUtil.check(RegexUtil.REGEX_UNICODECHAR, fleetLine.getFleetDescribe()))
                throw new BaseException("描述内容不合法");

        //判断该承运商是否拥有该分组
        EntityWrapper<Fleet> ew = new EntityWrapper<>();
        ew.eq("fleet_name", fleetLine.getFleetName());
        ew.eq("tenant_id", fleetLine.getTenantId());
        Fleet fleet = this.selectOne(ew);
        if (!Objects.isNull(fleet)) throw new BaseException("该分组已存在");
        //绑定剩余信息
        fleet = fleetLine;
        fleet.setCreator(jwtAccountVO.getAccountId());
        fleet.setGmtCreate(new Date());
        fleet.setIsDelete(0);
        fleet.setId(snowFlakeId.nextId());
        this.insert(fleet);
        Fleet finalFleet = fleet;
        finalFleet.setOilCardAccount(fleetLine.getOilCardAccount());
        //中联为四大家创建的车队推erp
        fleetToErpAndOtm(finalFleet, authorization);
        // 添加车队推送到油卡支付
        pushOilCardAccount(lspInfo.get(0).getName(), finalFleet);

        // 车队银行信息添加
//        EntityWrapper<FleetBankAccount> bankEW = new EntityWrapper<>();
//        bankEW.eq("fleet_id", fleet.getId());
//        bankEW.eq("is_delete", 0);
//        fleetBankAccountService.selectOne(bankEW);

        FleetBankAccount fleetBankAccount = new FleetBankAccount();
        fleetBankAccount.setFleetId(fleet.getId());
        fleetBankAccount.setLicenseId(fleetLine.getLicenseId());
        fleetBankAccount.setBankAccount(fleetLine.getBankAccount());
        fleetBankAccount.setBankAccountName(fleetLine.getBankAccountName());
        fleetBankAccount.setBankName(fleetLine.getBankName());
        fleetBankAccount.setTenantId(fleet.getTenantId());
        fleetBankAccount.setCreator(fleet.getCreator());
        fleetBankAccount.setOilCardAccount(fleetLine.getOilCardAccount());
        fleetBankAccount.setIsDelete(0);
        fleetBankAccountService.insert(fleetBankAccount);

        // 添加车队附件信息
        FleetLicenseAttach fleetAttach = new FleetLicenseAttach();
        fleetAttach.setTenantId(fleet.getTenantId());
        fleetAttach.setCreator(fleet.getCreator());
        fleetAttach.setIsDelete(0);
        fleetAttach.setFleetId(fleet.getId());
        // 添加身份证正面附件信息
        if (!StringUtils.isEmpty(fleetLine.getLicenseAttachKey())) {
            if (fleetLine.getLicenseAttachKey().equals(fleetLine.getLicenseAttachKey1())) {
                throw new BaseException("身份证正反照片不能一样！");
            }
            addFleetAttach(fleetAttach, fleetLine.getLicenseAttachKey(), fleetLine.getLicenseAttachName(), "01", "01");
        }

        // 添加身份证反面附件信息
        if (!StringUtils.isEmpty(fleetLine.getLicenseAttachKey1())) {
            addFleetAttach(fleetAttach, fleetLine.getLicenseAttachKey1(), fleetLine.getLicenseAttachName1(), "01", "02");
        }
        // 添加银行卡正面附件信息
        if (!StringUtils.isEmpty(fleetLine.getBankAttachKey())) {
            if (fleetLine.getBankAttachKey().equals(fleetLine.getBankAttachKey1())) {
                throw new BaseException("银行卡正反照片不能一样！");
            }
            addFleetAttach(fleetAttach, fleetLine.getBankAttachKey(), fleetLine.getBankAttachName(), "02", "01");
        }
        // 添加银行卡反面附件信息
        if (!StringUtils.isEmpty(fleetLine.getBankAttachKey1())) {
            addFleetAttach(fleetAttach, fleetLine.getBankAttachKey1(), fleetLine.getBankAttachName1(), "02", "02");
        }

    }

    public void pushOilCardAccount(String lspName, Fleet finalFleet) {
        if(!StringUtils.isEmpty(finalFleet.getOilCardAccount())){
            FleetToOliCardDTO fleetToOliCardDTO=new FleetToOliCardDTO();
            fleetToOliCardDTO.setCode(finalFleet.getId().toString());
            fleetToOliCardDTO.setAdministrator(finalFleet.getFleetName());
            fleetToOliCardDTO.setName(finalFleet.getFleetName());
            fleetToOliCardDTO.setMobile(finalFleet.getOilCardAccount());
            fleetToOliCardDTO.setCorpName(lspName);
            fleetToOliCardDTO.setProperty(finalFleet.getFleetTypeId().toString());
            String result=null;
            String json = JSONObject.toJSONString(fleetToOliCardDTO);
            try {
                LOGGER.info("FleetServiceImpl.insertFleet params:{},url:{}", json,integrationUrl+fleetPushPayUrl);
                RedisLogUtil.addSysLogs(SystemEnum.LSPM.getCode(),SystemEnum.INTEGRATION.getCode(),"fleet"+fleetToOliCardDTO.getCode(), JSON.toJSONString(fleetToOliCardDTO),"/oilCardPay/fleetPushPay",1,1,null,isTest);

                result = HttpClientUtil.postJson(integrationUrl+fleetPushPayUrl, null, json, socketTimeout);
                LOGGER.info("FleetServiceImpl.insertFleet result {}", result);
            } catch (Exception e) {
                LOGGER.error("FleetServiceImpl.insertFleet 连接超时 {}", e);
                throw new BaseException("车队推送万金油账号失败：" + e);
            }
            if (StringUtils.isEmpty(result)) {
                LOGGER.error("FleetServiceImpl.insertFleet 车队推送万金油账号,未响应 {}" + result);
                throw new BaseException("车队推送万金油账号响应：" + result);
            }else{
                Map<String,Object> map = (Map<String,Object>)JSONObject.parse(result);
                if(-1 == (int) map.get("code")){
                    throw new BaseException("车队推送万金油账号失败：" + map.get("message"));
                }
            }
        }
    }

    @Override
    public void fleetToErpAndOtm(Fleet fleet, String authorization) {

        new Thread(() -> {
            List<NameValuePair> headNamePairs = Lists.newArrayList();
            headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
            List<AccountVO> listTenantAccount = uaaUtil.getListTenantAccount(1l, authorization);
            for (AccountVO accountVO : listTenantAccount) {
                if (fleet.getCreator().equals(accountVO.getId().toString())) {
                    if (TableStatusEnum.STATUS_Y.getCode().equals(properties.getIntegrationToOtm())) {
                        //推送otm
                        LspInfoDTO lspInfoDTO = new LspInfoDTO();
                        lspInfoDTO.setFleetTypeId(fleet.getLspId().toString());
                        lspInfoDTO.setId(fleet.getId());
                        lspInfoDTO.setNameAbbr(fleet.getFleetName());
                        lspInfoDTO.setIsActive(IntegrationEnum.ISACTIVE.getCode());
                        lspInfoDTO.setName(fleet.getFleetName());
                        integrationUtil.exportLspToOTM(lspInfoDTO);
                    }
                    if (TableStatusEnum.STATUS_Y.getCode().equals(properties.getPushDataToERP())) {
                        //推送erp
                        FleetToOtmDTO fleetToOtmDTO = new FleetToOtmDTO();
                        fleetToOtmDTO.setId(fleet.getId());
                        fleetToOtmDTO.setName(fleet.getFleetName());
                        if (fleet.getFleetTypeId() == 2) {
                            fleetToOtmDTO.setProperty("3");
                        } else if (fleet.getFleetTypeId() == 1) {
                            fleetToOtmDTO.setProperty(String.valueOf(fleet.getFleetTypeId()));
                        } else {
                            fleetToOtmDTO.setProperty("2");
                        }
                        LOGGER.info("insertFleetToErp result {},params:{} ", integrationUrl + supplierPushErpUrl, JSONObject.toJSONString(fleetToOtmDTO));
                        String result = HttpClientUtil.postJson(integrationUrl + supplierPushErpUrl, headNamePairs, JSONObject.toJSONString(fleetToOtmDTO), socketTimeout);
                        LOGGER.info("insertFleetToErp result {},params:{} ", result, JSONObject.toJSONString(fleetToOtmDTO));
                        RedisLogUtil.addSysLogs(SystemEnum.LSPM.getCode(),SystemEnum.INTEGRATION.getCode(),"fleet"+fleetToOtmDTO.getId(), JSON.toJSONString(fleetToOtmDTO),"/erp-api/supplierPushErp",1,1,null,isTest);
                    }
                }
            }
        }).start();
    }

    /**
     * 修改车队信息
     */
    @Override
    @Transactional
    public Fleet updateFleet(Fleet fleetLine, String authorization) {

        if (Objects.isNull(fleetLine.getId())) throw new BaseException("未获取到需要修改的分组信息");
        EntityWrapper<Fleet> ew = new EntityWrapper<>();
        ew.eq("fleet_name", fleetLine.getId());
        ew.eq("lsp_id", fleetLine.getLspId());
        Fleet fleet = this.selectOne(ew);
        if (!Objects.isNull(fleet)) throw new BaseException("该分组已存在");
        this.updateById(fleetLine);
        //中联为四大家创建的车队推erp
        Fleet selectByIdNoTenant = this.selectByIdNoTenant(fleetLine.getId());
        fleetToErpAndOtm(selectByIdNoTenant, authorization);

        // 车队银行信息添加
        EntityWrapper<FleetBankAccount> bankEW = new EntityWrapper<>();
        bankEW.eq("fleet_id", fleetLine.getId());
        bankEW.eq("is_delete", 0);

        FleetBankAccount fleetBankAccount = fleetBankAccountService.selectOne(bankEW);
        if (null == fleetBankAccount) {
            fleetBankAccount = new FleetBankAccount();
        }

        // 万金油账号已经有则不进行更新
        if(StringUtils.isEmpty(fleetBankAccount.getOilCardAccount()) && !StringUtils.isEmpty(fleetLine.getOilCardAccount())){
            // 更新车队推送万金油账号
            LspInfo lspInfo = lspInfoService.selectByIdNoTenant(fleetLine.getLspId());
            pushOilCardAccount(lspInfo.getName(), fleetLine);

            fleetBankAccount.setOilCardAccount(fleetLine.getOilCardAccount());
        }

        fleetBankAccount.setFleetId(fleetLine.getId());
        fleetBankAccount.setLicenseId(fleetLine.getLicenseId());
        fleetBankAccount.setBankAccount(fleetLine.getBankAccount());
        fleetBankAccount.setBankAccountName(fleetLine.getBankAccountName());
        fleetBankAccount.setBankName(fleetLine.getBankName());
        fleetBankAccount.setTenantId(selectByIdNoTenant.getTenantId());
        fleetBankAccount.setCreator(AccountUtil.getAccountInfoFromSecurityContext().getAccountId());
        fleetBankAccountService.insertOrUpdate(fleetBankAccount);

        // 添加或更新车队附件信息
        // 先删除在添加
        EntityWrapper<FleetLicenseAttach> attachEW = new EntityWrapper<>();
        attachEW.eq("fleet_id", fleetLine.getId());
        fleetLicenseAttachService.delete(attachEW);

        FleetLicenseAttach fleetAttach = new FleetLicenseAttach();
        fleetAttach.setTenantId(selectByIdNoTenant.getTenantId());
        fleetAttach.setCreator(AccountUtil.getAccountInfoFromSecurityContext().getAccountId());
        fleetAttach.setIsDelete(0);
        fleetAttach.setFleetId(fleetLine.getId());
        // 添加身份证正面附件信息
        if (!StringUtils.isEmpty(fleetLine.getLicenseAttachKey())) {
            if (fleetLine.getLicenseAttachKey().equals(fleetLine.getLicenseAttachKey1())) {
                throw new BaseException("身份证正反照片不能一样！");
            }
            addFleetAttach(fleetAttach, fleetLine.getLicenseAttachKey(), fleetLine.getLicenseAttachName(), "01", "01");
        }

        // 添加身份证反面附件信息
        if (!StringUtils.isEmpty(fleetLine.getLicenseAttachKey1())) {
            addFleetAttach(fleetAttach, fleetLine.getLicenseAttachKey1(), fleetLine.getLicenseAttachName1(), "01", "02");
        }
        // 添加银行卡正面附件信息
        if (!StringUtils.isEmpty(fleetLine.getBankAttachKey())) {
            if (fleetLine.getBankAttachKey().equals(fleetLine.getBankAttachKey1())) {
                throw new BaseException("银行卡正反照片不能一样！");
            }
            addFleetAttach(fleetAttach, fleetLine.getBankAttachKey(), fleetLine.getBankAttachName(), "02", "01");
        }
        // 添加银行卡反面附件信息
        if (!StringUtils.isEmpty(fleetLine.getBankAttachKey1())) {
            addFleetAttach(fleetAttach, fleetLine.getBankAttachKey1(), fleetLine.getBankAttachName1(), "02", "02");
        }

        return fleetLine;

    }

    private FleetLicenseAttach addFleetAttach(FleetLicenseAttach fleetAttach, String attachKey,
                                              String attachName, String attachType, String attachStyle) {
        fleetAttach.setId(null);
        fleetAttach.setAttachKey(attachKey);
        fleetAttach.setAttachName(attachName);
        fleetAttach.setAttachType(attachType);
        fleetAttach.setAttachStyle(attachStyle);
        fleetLicenseAttachService.insert(fleetAttach);
        return fleetAttach;
    }

    /**
     * 删除车队
     *
     * @param
     */
    @Override
    public List<String> deleteFleet(List<Long> ids) {
        List<String> msg = new ArrayList<>();
        try {
            if (CollectionUtils.isEmpty(ids)) throw new BaseException("未选中所属承运商");
            for (Long id :
                    ids) {
                Fleet fleet = this.selectById(id);
                if (!Objects.isNull(fleet)) {
                    if (!(Objects.isNull(fleet.getIsDelete()) || fleet.getIsDelete().equals(0))) {
                        msg.add("名称:" + fleet.getFleetName() + ":" + "车队已删除");
                    } else {
                        try {
                            EntityWrapper<FleetBindVO> ew = new EntityWrapper<>();
                            ew.eq("fleet_id", fleet.getId());
                            List<FleetBindVO> carrierList = fleetBindService.queryBindCarrierList(ew);
                            List<FleetBindVO> trailerList = fleetBindService.queryBindTrailerList(ew);
                            List<FleetBindVO> driverList = fleetBindService.queryBindDriverList(ew);
                            if (!CollectionUtils.isEmpty(carrierList)) {
                                carrierList.forEach(fleetBindVO -> fleetBindService.deleteById(fleetBindVO.getId()));
                            }
                            if (!CollectionUtils.isEmpty(trailerList)) {
                                trailerList.forEach(fleetBindVO -> fleetBindService.deleteById(fleetBindVO.getId()));
                            }
                            if (!CollectionUtils.isEmpty(driverList)) {
                                driverList.forEach(fleetBindVO -> fleetBindService.deleteById(fleetBindVO.getId()));
                            }
                            this.deleteById(fleet);

                            // 删除车队银行信息添加
                            EntityWrapper<FleetBankAccount> bankEW = new EntityWrapper<>();
                            bankEW.eq("fleet_id", fleet.getId());
                            fleetBankAccountService.delete(bankEW);
                            //  删除车队附件信息
                            EntityWrapper<FleetLicenseAttach> attachEW = new EntityWrapper<>();
                            attachEW.eq("fleet_id", fleet.getId());
                            fleetLicenseAttachService.delete(attachEW);
                        } catch (Exception e) {
                            msg.add("名称:" + fleet.getFleetName() + ":" + "删除车辆错误");
                        }
                    }
                }

            }
        } catch (BaseException e) {
            LOGGER.error("FleetServiceImpl.deleteFleet:" + e.getMessage());
            throw e;
        } catch (Exception e) {
            LOGGER.error("FleetServiceImpl.deleteFleet:" + e.getMessage());
            throw new BaseException("删除车队失败!");
        }
        return msg;
    }

    /**
     * 车队批量新增车辆
     */
    @Override
    public void insertFleetBing(FleetLineVO fleetLineVO, String authorization) {
        if (CollectionUtils.isEmpty(fleetLineVO.getFleetBindIds())) {
            throw new BaseException("请选择要绑定的车辆");
        }
        for (Long fleetBindIds : fleetLineVO.getFleetBindIds()) {
            fleetBindService.insertFleetBind(fleetLineVO.getId(), fleetBindIds, authorization);
        }
    }

    /**
     * 车队批量删除车辆
     */
    @Override
    public void deleteFleetBing(FleetLineVO fleetLineVO) {
        if (CollectionUtils.isEmpty(fleetLineVO.getFleetBindIds())) {
            throw new BaseException("请选择要解绑的牵引车");
        }
        List<Long> fleetBindList=fleetLineVO.getFleetBindIds();
        for (Long fleetBindId : fleetBindList) {
            Driver driver = driverService.selectDriverByFleetBindId(fleetBindId);
            if (!Objects.isNull(driver)){
                List<NameValuePair> pram = Lists.newArrayList();
                pram.add(new BasicNameValuePair("DriverId", driver.getId().toString()));
                String driverWaybill = HttpClientUtil.get(driverWaybillUrl, null, pram, socketTimeout);
                if (!StringUtils.isEmpty(driverWaybill)) {
                    JSONObject driverWaybillJson = JSONObject.parseObject(driverWaybill);
                    if ("false".equals(driverWaybillJson.get("data").toString())) {
                        throw new BaseException("司机"+driver.getName()+"还有未完成的运单");
                    }
                }
                //校验司机是否有未安排的报班
                List<DriverCheckin> driverCheckins = driverCheckinService.selectByNowDayNoTenant(driver.getId());
                if (!CollectionUtils.isEmpty(driverCheckins)){
                    throw new BaseException("司机还有未安排的报班任务");
                }
            }
        }
        fleetBindService.deleteBatchIds(fleetLineVO.getFleetBindIds());
    }

    /**
     * 绑定信息接口
     */
    private EntityWrapper<FleetLineVO> buildCondition(Map<String, Object> condition) {
        EntityWrapper<FleetLineVO> ew = new EntityWrapper<>();
        if (!Objects.equals(condition, null)) {
            for (Map.Entry<String, Object> entry : condition.entrySet()) {
                if (Objects.nonNull(entry.getValue())) {
                    if (!StringUtils.isEmpty(entry.getValue().toString())) {
                        // 承运商名称
                        if (entry.getKey().equals("lspName")) {
                            ew.like("lsp_name", entry.getValue().toString());
                        }
                        // 车队名称
                        if (entry.getKey().equals("fleetName")) {
                            ew.like("fleet_name", entry.getValue().toString());
                        }
                    }
                }
            }
        }
        ew.orderBy("id", false);
        return ew;
    }

    @Override
    public List<Fleet> selectFleetList(Map<String, Object> condition) {
        EntityWrapper<Fleet> fleetEntityWrapper = this.buildFleetCondition(condition);
        return this.selectList(fleetEntityWrapper);
    }

    private EntityWrapper<Fleet> buildFleetCondition(Map<String, Object> condition) {
        EntityWrapper<Fleet> ew = new EntityWrapper<>();
        if (condition != null) {
            for (Map.Entry<String, Object> entry : condition.entrySet()) {
                if (!StringUtils.isEmpty(entry.getValue())) {
                    // 承运商id
                    if (entry.getKey().equals("lspId")) {
                        ew.eq("lsp_id", entry.getValue().toString());
                    }
                    // 车队名称
                    if (entry.getKey().equals("fleetName")) {
                        ew.like("fleet_name", entry.getValue().toString());
                    }
                    // 车队名称
                    if (entry.getKey().equals("personal")) {
                        ew.like("personal", entry.getValue().toString());
                    }
                }
            }
        }
        ew.orderBy("id", false);
        return ew;
    }

    @Override
    public List<FleetLineVO> queryFleetBindList(Wrapper<FleetLineVO> ew) {
        return baseMapper.queryFleetBindList(ew);
    }


    @Override
    public String fleetToOtm(Long id, String authorization) {
        Fleet fleet = this.selectById(id);
        List<AccountVO> listTenantAccount = uaaUtil.getListTenantAccount(1l, authorization);
        for (AccountVO accountVO : listTenantAccount) {
            if (fleet.getCreator().equals(accountVO.getId().toString())) {
                LspInfoDTO lspInfoDTO = new LspInfoDTO();
                lspInfoDTO.setFleetTypeId(fleet.getLspId().toString());
                lspInfoDTO.setId(fleet.getId());
                lspInfoDTO.setNameAbbr(fleet.getFleetName());
                lspInfoDTO.setIsActive(IntegrationEnum.ISACTIVE.getCode());
                String result = integrationUtil.exportLspToOTM(lspInfoDTO);
                return result;
            }
        }
        throw new BaseException("不属于中联创建的车队");
    }

    /**
     * 根据车队名称获取车队信息
     *
     * @param arFundDTOS
     * @return
     */
    @Override
    public Map<Long, Fleet> queryFleetByName(List<ArFundDTO> arFundDTOS) {
        Map<Long, Fleet> map = Maps.newHashMap();
        if (!CollectionUtils.isEmpty(arFundDTOS)) {
            for (ArFundDTO arFundDTO : arFundDTOS) {
                if (!Objects.isNull(arFundDTO)) {
                    EntityWrapper<Fleet> ew = new EntityWrapper<>();
                    ew.eq("fleet_name", arFundDTO.getFleetName());
                    List<Fleet> fleets = baseMapper.selectListNoTenant(ew);
                    if (!CollectionUtils.isEmpty(fleets))
                        map.put(arFundDTO.getId(), fleets.get(0));
                }
            }
        }
        return map;
    }

    @Override
    public List<Fleet> getFleetAll(List<Fleet> fleetList) {
        if (fleetList.isEmpty()) return null;
        List<Fleet> list = Lists.newArrayList();
        fleetList.forEach(fleet -> {
            HashMap<String, Object> map = Maps.newHashMap();
            map.put("fleetName", fleet.getFleetName());
            EntityWrapper<Fleet> ew = this.queryLspInfoCheck(map);
            Fleet resultData = baseMapper.selectNoTenant(ew);
            if (!ObjectUtils.isEmpty(resultData)) {
                list.add(resultData);
            }
        });
        return list;
    }

    /**
     * 车队查询条件
     *
     * @param condition 模糊查询字段
     * @return
     */
    private EntityWrapper<Fleet> queryLspInfoCheck(Map<String, Object> condition) {
        EntityWrapper<Fleet> ew = new EntityWrapper<>();
        if (!CollectionUtils.isEmpty(condition)) {
            //遍历条件
            for (Map.Entry<String, Object> entry : condition.entrySet()) {
                if (!Strings.isNullOrEmpty(entry.getKey())) {
                    //车队名称
                    if ("fleetName".equals(entry.getKey()) && !StringUtils.isEmpty(entry.getValue()))
                        ew.eq("fleet_name", String.valueOf(entry.getValue()));
                }
            }
        }
        return ew;
    }

    /**
     * 无tenant 查询车队
     */
    @Override
    public Fleet selectByIdNoTenant(Long fleetId) {
        return baseMapper.selectByIdNoTenant(fleetId);
    }

    @Override
    public Page<FleetManagementListVO> FleetManagementList(Page<FleetManagementListVO> page, String
            authorization) {
        Map<String, Object> condition = page.getCondition();
        Wrapper<FleetManagementListVO> fleetManagementListVOWrapper = new EntityWrapper<>();
        if (StringUtils.isEmpty(condition.get("id"))) throw new BaseException("不是车队管理员,不能进行此操作!");

        String id = condition.get("id").toString();
        String[] split = id.split(",");
        List<String> strings = Arrays.asList(split);
        fleetManagementListVOWrapper.in("lf.id", strings);
        if (!StringUtils.isEmpty(condition.get("lspName"))) {
            fleetManagementListVOWrapper.like("lli.name", condition.get("lspName").toString());
        }
        if (!StringUtils.isEmpty(condition.get("fleetName"))) {
            fleetManagementListVOWrapper.like("lf.fleet_name", condition.get("fleetName").toString());
        }
        if (!StringUtils.isEmpty(condition.get("mobile"))) {
            fleetManagementListVOWrapper.like("ld.mobile", condition.get("mobile").toString());
        }
        return page.setRecords(baseMapper.FleetManagementList(page, fleetManagementListVOWrapper));
    }

    @Override
    public List<Fleet> selectListNoTenant(EntityWrapper<Fleet> fEW) {
        return baseMapper.selectListNoTenant(fEW);
    }

    @Override
    public Fleet getOneFleet(Fleet fleet) {
        return baseMapper.selectOne(fleet);
    }

    @Override
    public List<FleetCarId> getOldFleetByCarrierIdOrTrailerIdNoTenant(Long carrierId, Long trailerId) {
        return baseMapper.selectOldFleetByCarrierIdOrTrailerIdNoTenant(carrierId, trailerId);
    }

    @Override
    public FleetCarId getNewFleetByCarrierIdOrTrailerIdNoTenant(Long carrierId, Long trailerId) {
        return baseMapper.selectNewFleetByCarrierIdOrTrailerIdNoTenant(carrierId, trailerId);
    }

    @Override
    public Fleet getFleetAttach(Long id) {
        Wrapper<FleetLicenseAttach> attachEW = new EntityWrapper<>();
        attachEW.eq("fleet_id", id);
        List<FleetLicenseAttach> fleetLicenseAttachs = fleetLicenseAttachService.selectListNoTenant(attachEW);
        if (null == fleetLicenseAttachs || fleetLicenseAttachs.isEmpty()) {
            return null;
        }
        Fleet fleet = new Fleet();
        for (FleetLicenseAttach attach : fleetLicenseAttachs) {
            if (StringUtils.isEmpty(attach.getAttachType())) {
                continue;
            }
            if ("01".equals(attach.getAttachType())) {// 身份证
                if ("01".equals(attach.getAttachStyle())) {// 正面
                    fleet.setLicenseAttachKey(attach.getAttachKey());
                    fleet.setLicenseAttachName(attach.getAttachName());
                    fleet.setLicenseAttachStyle(attach.getAttachStyle());
                    fleet.setLicenseAttachType(attach.getAttachType());
                    fleet.setLicenseAttachPath(getAttachPath(attach.getAttachKey(), attach.getAttachName()));
                } else {// 反面
                    fleet.setLicenseAttachKey1(attach.getAttachKey());
                    fleet.setLicenseAttachName1(attach.getAttachName());
                    fleet.setLicenseAttachStyle1(attach.getAttachStyle());
                    fleet.setLicenseAttachType1(attach.getAttachType());
                    fleet.setLicenseAttachPath1(getAttachPath(attach.getAttachKey(), attach.getAttachName()));
                }
            } else {// 银行卡
                if ("01".equals(attach.getAttachStyle())) {// 正面
                    fleet.setBankAttachKey(attach.getAttachKey());
                    fleet.setBankAttachName(attach.getAttachName());
                    fleet.setBankAttachStyle(attach.getAttachStyle());
                    fleet.setBankAttachType(attach.getAttachType());
                    fleet.setBankAttachPath(getAttachPath(attach.getAttachKey(), attach.getAttachName()));
                } else {// 反面
                    fleet.setBankAttachKey1(attach.getAttachKey());
                    fleet.setBankAttachName1(attach.getAttachName());
                    fleet.setBankAttachStyle1(attach.getAttachStyle());
                    fleet.setBankAttachType1(attach.getAttachType());
                    fleet.setBankAttachPath1(getAttachPath(attach.getAttachKey(), attach.getAttachName()));
                }
            }
        }
        return fleet;
    }

    private String getAttachPath(String attachKey, String attachName) {

        String lookUrl = QiniuUtils.generateDownloadTicket(qiniuConfig.getDownloadUrl(), attachKey);
        // 下载地址
        String downloadUrl = lookUrl + "&attname=" + attachName;
        return lookUrl;
    }

    @Override
    public List<Fleet> selectFleetByIds(List<Long> ids) {
        EntityWrapper<Fleet> fleetEW = new EntityWrapper<>();
        fleetEW.in("id", ids);
        return baseMapper.selectFleetByIds(fleetEW);
    }

    @Override
    public Map<String, Object> getAttachPatch(String key) {
        Map<String, Object> map = new HashMap<>();
        String url = QiniuUtils.generateDownloadTicket(qiniuConfig.getDownloadUrl(), key);
        map.put("lookUrl", url);
        return map;
    }

    @Override
    public Fleet selectByResourceIdAndType(String type, Long id) {
        return baseMapper.selectOneByResourceIdAndType(type, id);
    }

    @Override
    public FleetLineVO queryFleetBasic(Map<String, String> condition) {
        if (condition == null || condition.isEmpty()) {
            throw new BaseException("参数不能为空");
        }
        Wrapper<FleetLineVO> ew = new EntityWrapper<>();
        ew.eq("id", condition.get("fleetId"));
        List<FleetLineVO> vos = baseMapper.queryFleetBasicNoTenant(ew);
        if (!CollectionUtils.isEmpty(vos)) {
            return vos.get(0);
        }
        return null;
    }

    @Override
    public List<Fleet> selectFleetListByLspMobile(String mobile) {
        if(null == mobile || "".equals(mobile)){return null;}

        return baseMapper.selectFleetByLspMobile(mobile);
    }

    @Override
    public Map<String, Object> queryPersonalByFleetName(String fleetName) {
        Wrapper<Fleet> ew = new EntityWrapper<>();
        Map<String, Object> map=new HashMap<>();
        String personal="";
        if (fleetName!=null && !"".equals(fleetName)){
            ew.like("fleet_name",fleetName);
            List<Fleet> fleets = baseMapper.selectList(ew);
            if(CollectionUtils.isEmpty(fleets)){
                personal=null;
            }else {
                personal=fleets.get(0).getPersonal();
                Date gmtUpdate =fleets.get(0).getGmtUpdate();
                if (personal!=null && !"".equals(personal)){
                    map.put("personal",personal);
                    map.put("gmtUpdate",gmtUpdate);
                    if (isNumLegal(fleets.get(0).getFleetDescribe())){
                        String mobile=fleets.get(0).getFleetDescribe();
                        map.put("mobile",mobile);
                        return map;
                    }else {
                        String mobile=fleetAdminService.selectFleetAdminByName(personal);
                        map.put("mobile",mobile);
                        return map;
                    }

                }
            }
            return map;
        }
        return map;
    }

    @Override
    public List<Fleet> queryByFleetName(String fleetName) {
        Wrapper<Fleet> ew = new EntityWrapper<>();
        if (fleetName!=null && !"".equals(fleetName)){
            ew.like("fleet_name",fleetName);
        }
        List<Fleet> map=baseMapper.selectList(ew);
        return map;
    }


    @Override
    public String disableFleet(FleetVo condition,String authorization) {
        if (StringUtils.isEmpty(condition.getFleetId()) ){
            throw new BaseException("车队id不能为空");
        }

        //判断该车队是否有未安排(40)的报班任务
        List<DriverCheckin> driverCheckins=driverCheckinService.selectCheckinByFleetId(condition.getFleetId());
        if (!CollectionUtils.isEmpty(driverCheckins)){
            throw new BaseException("车队还有未安排的报班任务");
        }

        //判断车队下司机是否有未完成的任务
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", authorization));


        String url=fleetWaybillUrl+"?fleetId="+condition.getFleetId();
        String fleetWaybill = HttpClientUtil.get(url, headNamePairs, null, socketTimeout);
        JSONObject lspWaybillJson = JSONObject.parseObject(fleetWaybill);
        String data=lspWaybillJson.get("data").toString();
        if ("false".equals(data) && org.apache.commons.lang3.StringUtils.isNotBlank(data)) {
            throw new BaseException("车队下的司机还有未完成的运单");
        }


        // 更新车队的业务状态
        if ("1".equals(condition.getIsDelete())){
            throw new BaseException("车队已禁用");
        }


        Fleet fleet = new Fleet();
        fleet.setId(Long.parseLong(condition.getFleetId()));
        fleet.setIsDelete(1);
        baseMapper.updateById(fleet);

        Fleet fleet1 = this.selectById(condition.getFleetId());
        if (Objects.isNull(fleet1)) {
            throw new BaseException("未获取到车队");
        }

        LspInfoDTO lspInfoDTO = new LspInfoDTO();
        lspInfoDTO.setFleetTypeId(fleet1.getLspId().toString());
        lspInfoDTO.setId(fleet1.getId());
        lspInfoDTO.setNameAbbr(fleet1.getFleetName());
        lspInfoDTO.setName(fleet1.getFleetName());
        lspInfoDTO.setIsActive(IntegrationEnum.NOACTIVE.getCode());
        String result = integrationUtil.exportLspToOTM(lspInfoDTO);
        return result;

    }

    @Override
    public String enableFleet(FleetVo condition,String authorization) {
        if (StringUtils.isEmpty(condition.getFleetId()) ){
            throw new BaseException("车队id不能为空");
        }

        // 更新车队的业务状态
        if (0==condition.getIsDelete()){
            throw new BaseException("车队已启用");
        }


        Fleet fleet = new Fleet();
        fleet.setId(Long.parseLong(condition.getFleetId()));
        fleet.setIsDelete(0);
        baseMapper.updateById(fleet);

        Fleet fleet1 = this.selectById(condition.getFleetId());
        if (Objects.isNull(fleet1)) {
            throw new BaseException("未获取到车队");
        }

        LspInfoDTO lspInfoDTO = new LspInfoDTO();
        lspInfoDTO.setFleetTypeId(fleet1.getLspId().toString());
        lspInfoDTO.setId(fleet1.getId());
        lspInfoDTO.setNameAbbr(fleet1.getFleetName());
        lspInfoDTO.setName(fleet1.getFleetName());
        lspInfoDTO.setIsActive(IntegrationEnum.ISACTIVE.getCode());
        String result = integrationUtil.exportLspToOTM(lspInfoDTO);
        return result;

    }

    @Override
    public Page<FleetVo> lspFleetList(Page<Map<String, Objects>> page, String authorization) {
        Page<FleetVo> pageVo = new Page<>();

        Map<String, Object> condition = page.getCondition();

        EntityWrapper<Fleet> ew = new EntityWrapper<>();
        if (null != condition.get("fleetName") && !StringUtils.isEmpty(condition.get("fleetName"))) {
            ew.like("a.fleet_name", condition.get("fleetName").toString());
        }
        if (null != condition.get("isDelete") && !StringUtils.isEmpty(condition.get("isDelete"))) {
            ew.eq("a.is_delete", condition.get("isDelete").toString());
        }

        List<FleetVo> maps = baseMapper.getFleetList(page, ew);

        List<FleetTypeVO> listFleetType = mdmUtil.getAllFleetTypeByType();

        for (FleetVo fleetVo : maps) {
            for (FleetTypeVO fleetType : listFleetType) {
                if (fleetType.getId().equals(fleetVo.getFleetTypeId())) {
                    fleetVo.setFleetType(fleetType.getValue());
                }
            }
        }
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(maps);
        return pageVo;
    }

    @Override
    public List<Fleet> selectFleetListByMobile(String tenantId) {
        EntityWrapper<Fleet> fleetEntityWrapper =new EntityWrapper<>();
        fleetEntityWrapper.eq("tenant_id",tenantId);
        return  baseMapper.selectList(fleetEntityWrapper);
    }

    /** 正则表达
     * 手机号码由11位数字组成，
     * 匹配格式：前三位固定格式+后8位任意数
     * 此方法中前三位格式有：
     * 13+任意数
     * 15+除4的任意数
     * 18+除1和4的任意数
     * 17+除9的任意数
     * 147
     */
    private  boolean isNumLegal(String str) throws PatternSyntaxException {
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$");
        Matcher m = p.matcher(str);
        return m.matches();
    }


}
